package cn.c3n.demo.controller;

import cn.c3n.demo.domain.Girl;
import cn.c3n.demo.domain.Result;
import cn.c3n.demo.repository.GirlRepository;
import cn.c3n.demo.service.GirlService;
import cn.c3n.demo.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
public class GirlController {

    private final static Logger logger = LoggerFactory.getLogger(GirlController.class);

    @Autowired
    GirlRepository girlRepository;

    @Autowired
    GirlService girlService;

    @GetMapping(value = "/girls")
    public List<Girl> girlList(){
        logger.info("9999999999999999999");
        return girlRepository.findAll();
    }

    /**
     * 添加一个女生
     * @return
     */
    @PostMapping(value = "/girls")
    public Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult)
    {
        if(bindingResult.hasErrors())
        {
            return ResultUtil.error(1, bindingResult.getFieldError().getDefaultMessage());
        }
        girl.setAge(girl.getAge());
        girl.setCupSize(girl.getCupSize());

        return ResultUtil.success(girlRepository.save(girl));
    }

    //查询
    @GetMapping(value ="/girls/{id}")
    public Girl girlFindOne(@PathVariable("id")Integer id)
    {
        return girlRepository.findOne(id);
    }

    //更新
    @PutMapping(value ="/girls/{id}")
    public Girl girlUpdate(@PathVariable Integer id, @RequestParam("cupSize")String cupSize, @RequestParam("age")Integer age){
        Girl girl = new Girl();
        girl.setId(id);
        girl.setCupSize(cupSize);
        girl.setAge(age);
        return girlRepository.save(girl);
    }

    //删除
    @DeleteMapping(value ="/girls/{id}")
    public void girlDelete(@PathVariable("id") Integer id)
    {
        girlRepository.delete(id);
    }

    /**
     * 通过年龄查询女生列表
     * @param age
     * @return
     */
    @GetMapping(value = "/girls/age/{age}")
    public List<Girl> girlListByAge(@PathVariable("age") Integer age)
    {
        return girlRepository.findByAge(age);
    }

    @PostMapping(value = "/girls/two")
    public void girlTwo()
    {
        girlService.insertTwo();
    }

    @GetMapping(value = "/girls/getAge/{id}")
    public void getAge(@PathVariable("id") Integer id) throws Exception
    {
        girlService.getAge(id);
    }

}
